package com.yubest.demo.util;

import cn.hutool.crypto.SecureUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yubest.demo.dto.DemoRespDTO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Base64;

/**
 * @program: spring-boot-encrypt
 * @ClassName AESUtil
 * @description: aes加解密工具类
 * @author: 黄涛
 * @create: 2023-12-01 10:01
 * @Version 1.0
 **/
@Component
public class AESUtil {


    private static String secret;

    @Value("${safety.secret}")
    private String secret_;

    @PostConstruct
    private void init() {
        this.secret = secret_;
    }


    //region 加密
    /**
     * 加密
     * @param obj
     * @return
     */
    public static String encode(Object obj) {
        ObjectMapper om = new ObjectMapper();
        try {
            String objStr = om.writeValueAsString(obj);
            String  encode = SecureUtil.aes(secret.getBytes()).encryptHex(objStr);
            return encode;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
       return null;
    }
    //endregion


    //region 解密
    /**
     * 解密
     * @param str
     * @return
     */
    public static String decode(String str) {
        String  decode = SecureUtil.aes(secret.getBytes()).decryptStr(str);
        return decode;
    }

    public static byte[] decodeByte(String str) {
        String decryptStr = SecureUtil.aes(secret.getBytes()).decryptStr(str);
        byte[] byBuffer= decryptStr.getBytes();
        return byBuffer;
    }
    //endregion



    public static void main(String[] args) {
        String obj = null;
        DemoRespDTO respDTO = new DemoRespDTO().setC(3).setD("4");
        ObjectMapper om = new ObjectMapper();
        try {

            obj = om.writeValueAsString(respDTO);
            obj = "{\"sign\":\"1\",\"timestamp\":\"2\",\"version\":\"3\",\"data\":\"4\"}";


            //使用hutool工具
            //aes加密,输出16进制
           String  jsondata = SecureUtil.aes("._^BV67nW6ck8fwg".getBytes()).encryptHex(obj);
           System.out.println(jsondata);

            //aes解密密,输出16进制
            String  decryptStr = SecureUtil.aes("._^BV67nW6ck8fwg".getBytes()).decryptStr(jsondata);
            System.out.println(decryptStr);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
